package com.white.hot.controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.white.hot.dto.CrashLog;
import com.white.hot.dto.resp.BaseResp;
import com.white.hot.dto.resp.MapInfo;
import com.white.hot.service.CrashLogService;
import com.white.hot.utils.TextUtils;

@Controller
@EnableWebMvc
@RequestMapping("/access")
public class FileDownloadController extends BaseController
{
	@Resource
	private CrashLogService crashLogService;
	
	@RequestMapping(value="/logList")
	public ModelAndView  listAllFile(HttpServletRequest req, HttpServletResponse response) throws IOException
	{
		List<CrashLog> list = crashLogService.getList(null, null,null,null,null);
		return new ModelAndView("LogList","list",list);
	}
	
	@RequestMapping(value="/logDList")
	@ResponseBody
	public Object  listSelectFile(
			@RequestParam(required = false,value = "startTime") String startTime, 
			@RequestParam(required = false,value = "endTime") String endTime, 
			@RequestParam(required = false,value = "brand") String brand, 
			@RequestParam(required = false,value = "model") String model, 
			@RequestParam(required = false,value = "api") String api, 
			HttpServletRequest req, HttpServletResponse response) throws IOException
	{
		BaseResp br = new BaseResp();
		List<CrashLog> list = null;
		String param[] = new String[5];
		Arrays.fill(param, null);
		if(!TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime))
		{
			param[0] = startTime;
			param[1] = endTime;
		}else if(TextUtils.isEmpty(startTime) && !TextUtils.isEmpty(endTime))
		{
			param[0] = null;
			param[1] = endTime;
		}else if(TextUtils.isEmpty(endTime) && !TextUtils.isEmpty(startTime))
		{
			param[0] = startTime;
			param[1] = null;
		}else
		{
			param[0] = null;
			param[1] = null;
		}
		if(!TextUtils.isEmpty(brand) && !brand.contains("手机"))
			param[2] = brand;
		if(!TextUtils.isEmpty(model) && !model.contains("手机"))
			param[3] = model;
		if(!TextUtils.isEmpty(api) && !api.contains("系统"))
			param[4] = api;
		list = crashLogService.getList(param[0], param[1], param[2], param[3], param[4]);
		br.rows = list;
		br.total = list == null ? 0 : list.size();			
		buildSuccessResp(br);
		return br;
	}
	
	@RequestMapping(value="/logFile/**")
	public void readFile(HttpServletRequest req, HttpServletResponse resp) throws IOException
	{
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		String reqPath = req.getRequestURI();
		int s = reqPath.indexOf("/logFile");
		int e = reqPath.lastIndexOf("/");
		String logRelaticePath = reqPath.substring(s + 9, e);
		String crashRoot = req.getSession().getServletContext().getRealPath(logRelaticePath);
		String fileName = reqPath.substring(e+1, reqPath.length());
		fileName = URLDecoder.decode(fileName, "utf-8"); 
		File f = new File(crashRoot + "/" + fileName);
		if(f.exists())
		{
			FileInputStream fis = new FileInputStream(f);
			InputStreamReader re = new InputStreamReader(fis, "utf-8");
			BufferedReader br = new BufferedReader(re);
			PrintWriter wr = resp.getWriter();
			String str;
			while((str = br.readLine()) != null)
			{
				str = str + "\n";
				wr.write(str);				
			}
			wr.flush();
			wr.close();
			br.close();
		}
	}
	
	String idRegax = "^\\d+$";
	
	@RequestMapping(value="/logFileDetail")
	@ResponseBody Object update(@RequestParam(value = "id") String id, HttpServletRequest req, HttpServletResponse response) throws Exception
	{
		BaseResp bs = new BaseResp();
		if(!TextUtils.isEmpty(id) && id.matches(idRegax))
		{
			
			CrashLog cl = crashLogService.load(Integer.parseInt(id));
			if(cl != null)
			{
				String crashRoot = req.getSession().getServletContext().getRealPath("uploadFiles/");
				String logPath = cl.getLogUrl(); 
				int s = logPath.indexOf("/") + 1;
				logPath = crashRoot + "/" + logPath.substring(s, logPath.length());
				File f = new File(logPath);
				if(f.exists())
				{
					FileInputStream fis = new FileInputStream(f);
					InputStreamReader re = new InputStreamReader(fis, "utf-8");
					BufferedReader br = new BufferedReader(re);
					StringBuffer sb = new StringBuffer();
					String str;
					while((str = br.readLine()) != null)
					{
						sb.append(str + "<br/>");
					}
					br.close();
					cl.setLogUrl(sb.toString());
				}
				MapInfo mi = new MapInfo();
				mi.other = cl;
				bs.setMapInfo(mi);
				return buildSuccessResp(bs);				
			}
		}
		return buildParamIllegalResp(bs);
	}
	
	@RequestMapping(value="/categary")
	@ResponseBody Object getCategary(@RequestParam(value = "cat") int cat,HttpServletRequest req, HttpServletResponse response) throws Exception
	{
		BaseResp bs = new BaseResp();
		List<String> list = crashLogService.getCategary(cat);
		bs.rows = list;
		bs.total = list == null ? 0 : list.size();
		return buildSuccessResp(bs);
	}
	
	@RequestMapping(value="/xiug")
	@ResponseBody Object update(HttpServletRequest req, HttpServletResponse response) throws Exception
	{
		BaseResp br = new BaseResp();
		String crashRoot = req.getSession().getServletContext().getRealPath("uploadFiles/CrashLog/sxb/");
		List<CrashLog> list = crashLogService.getList(null, null,null,null,null);
		for(Iterator<CrashLog> it = list.iterator() ; it.hasNext();)
		{
			CrashLog cl = it.next();
			String pth = cl.getLogUrl();
			int s = pth.lastIndexOf("/");
			String a = crashRoot + "/" + pth.substring(s+1, pth.length());
			File f = new File(a);		
			if(f.exists())
			{
				FileInputStream fis = new FileInputStream(f);
				InputStreamReader re = new InputStreamReader(fis, "utf-8");
				BufferedReader bfr = new BufferedReader(re);
				String str;
				boolean hasChanged = false;
				while((str = bfr.readLine()) != null)
				{
					if(!TextUtils.isEmpty(str))
					{
						if(str.contains("Android Platform"))
						{
							int ss = str.indexOf(":") + 1;
							String api = str.substring(ss, str.length()).trim();
							api = api.replace(" ", "");
							cl.setLogDeviceApi(api);
							hasChanged = true;
						}
						if(str.contains("MODEL"))
						{
							int ss = str.indexOf(":") + 1;
							String model = str.substring(ss, str.length());
							model = model.replace(" ", "");
							cl.setLogDeviceModel(model);
							hasChanged = true;
						}
						if(str.contains("BRAND"))
						{
							int ss = str.indexOf(":") + 1;
							String brand = str.substring(ss, str.length());
							brand = brand.replace(" ", "");
							cl.setLogDeviceBrand(brand);
							hasChanged = true;
						}
						if(hasChanged)
							crashLogService.update(cl);
					}
				}
				bfr.close();				
			}
		}		
		return buildSuccessResp(br);
	}
}
